package com.kky.pp.activity.wlm

import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.kky.pp.common.Constant
import io.rong.imkit.SpName
import com.kky.pp.adapter.WhoLikeMeAdapter
import io.rong.imkit.animator.recyclerview.SlideInLeftAnimator
import com.kky.pp.bean.WhoLikeMeListBean
import com.kky.pp.callback.EmptyCallBack
import com.kky.pp.callback.EmptySuccessCallBack
import com.kky.pp.callback.WLMSwipedCallBack
import com.kky.pp.popup.MemberBuyPopup
import com.kky.pp.entity.BaseEntity
import com.kky.pp.entity.MemberSubscribeEntity
import io.rong.imkit.entity.OrderCreateEntity
import com.kky.pp.entity.WhoLikeMeEntity
import com.kky.pp.http.code.HttpResultCode
import io.rong.imkit.event.EnumEventTag
import io.rong.imkit.event.FirebaseEventTag
import com.kky.pp.activity.match.MatchedActivity
import com.kky.pp.activity.me.info.ProfileInfoActivity
import com.kky.pp.util.CollectionUtils
import com.kky.pp.view.Loading.LoadingDialog
import io.rong.imkit.utils.FirebaseEventUtils
import com.kky.pp.pay.GooglePayUtils
import com.custom.base.config.BaseConfig
import com.custom.base.entity.OkHttpBodyEntity
import com.custom.base.entity.PageModel
import com.custom.base.http.OkHttpFromBoy
import com.custom.base.http.OkHttpManager
import com.custom.base.http.SDOkHttpResoutCallBack
import com.custom.base.manager.SDActivityManager
import com.custom.base.mvp.BasePresenterImpl
import com.custom.base.util.IntentUtil
import com.kky.pp.R
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.custom.base.base.SDEventManager


class WhoLikeMePresenter : BasePresenterImpl<WhoLikeMeContract.View>(), WhoLikeMeContract.Presenter {
    private var data: WhoLikeMeEntity.Data? = null
    private var member: Boolean = false
    var list = arrayListOf<WhoLikeMeListBean>()
    var page = PageModel()
    var whoLikeMeAdapter: WhoLikeMeAdapter? = null
    var wlmNum = 0
    var message = ""

    override fun initBundle(bundle: Bundle) {
        mView?.apply {
            refreshLayoutLikeMeFrag.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
                override fun onRefresh(refreshLayout: RefreshLayout) {
                    page.initialRefresh()
                    getData()
                }

                override fun onLoadMore(refreshLayout: RefreshLayout) {
                    page.nextPage()
                    getData()
                }

            })
            whoLikeMeAdapter = WhoLikeMeAdapter(list, mActivity, object : WLMSwipedCallBack {
                override fun swipedCallback(direction: Int, whoLikeMeListBean: WhoLikeMeListBean) {
                    FirebaseEventUtils.logEvent(if (direction == ItemTouchHelper.START) FirebaseEventTag.WLM_Pass.name else FirebaseEventTag.WLM_Like.name)
                    benefitsReduceWLM(
                        whoLikeMeListBean.userCodeFriend,
                        if (direction == ItemTouchHelper.START) 2 else 1,
                        object : EmptyCallBack {
                            override fun OnSuccessListener() {
                                userAction(direction, whoLikeMeListBean)
                            }

                            override fun OnFailListener() {
                                getData()
                            }

                        })
                }

                override fun swipedRefresh() {
                    getData()
                }

            })
            rvLikeMeList.apply {
                itemAnimator = SlideInLeftAnimator()
                adapter = whoLikeMeAdapter
                layoutManager = LinearLayoutManager(mActivity)
            }
//            val swipeCardCallback = SwipeCardCallback(
//                whoLikeMeAdapter,
//                object : WLMSwipedCallBack {
//                    override fun swipedCallback(direction: Int, wlmListBean: WhoLikeMeListBean) {
//                        userAction(direction, wlmListBean)
//                    }
//
//                    override fun swipedRefresh() {
//                        getData()
//                    }
//                })
//            val helper = ItemTouchHelper(swipeCardCallback)
//            helper.attachToRecyclerView(whoLikeMeList)
            if (bundle.getSerializable("wlmData") != null) {
                data = bundle.getSerializable("wlmData") as WhoLikeMeEntity.Data
                initData(data)
            } else {
                LoadingDialog.showLoading(mActivity)
                page.request(object : OkHttpFromBoy {
                    override fun addBody(requestBody: OkHttpBodyEntity) {
                        requestBody.setPost(Constant.user_wlm_list_url)
                        requestBody.addPage(page)
                    }
                }, object : SDOkHttpResoutCallBack<WhoLikeMeEntity>() {
                    override fun onSuccess(entity: WhoLikeMeEntity) {
                        LoadingDialog.dismissLoading(mActivity)
                        data = entity.data
                        initData(data)

                    }

                    override fun onFinish() {
                        LoadingDialog.dismissLoading(mActivity)
                        page.onRefreshComplete()
                    }
                })
            }
            txtLikeMeFragEdit.setOnClickListener {
                IntentUtil.startActivity(ProfileInfoActivity::class.java)
            }
            txtLikeMeFragPremiumUnlock.setOnClickListener {
                SDEventManager.post(EnumEventTag.CHAT_LIST_ITEM.ordinal)
                FirebaseEventUtils.logEvent(FirebaseEventTag.WLM_Unlock_Sub.name)
                MemberBuyPopup(
                    SDActivityManager.instance.lastActivity,
                    1,
                    object : MemberBuyPopup.ChangeMembershipListener {
                        override fun onListener(bean: MemberSubscribeEntity.Data.ProductDescriptions) {
                            OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                                override fun addBody(requestBody: OkHttpBodyEntity) {
                                    requestBody.setPost(Constant.user_create_order_url)
                                    requestBody.add("productCode", bean.productCode)
                                    requestBody.add("productCategory", 1)
                                }

                            }, object : SDOkHttpResoutCallBack<OrderCreateEntity>() {
                                override fun onSuccess(entity: OrderCreateEntity) {
                                    GooglePayUtils.instance.start(
                                        entity,
                                        mActivity,
                                        object : EmptySuccessCallBack {
                                            override fun OnSuccessListener() {
                                                page.initialRefresh()
                                                getData()
                                                BaseConfig.getInstance.setBoolean(
                                                    SpName.isMember,
                                                    true
                                                )
                                                FirebaseEventUtils.logEvent(FirebaseEventTag.WLM_Unlock_Subsuccess.name)
                                            }

                                        })
                                }
                            })
                        }

                        override fun closeListener(refreshTime: Long) {

                        }

                    })
            }

        }
    }

    private fun WhoLikeMeContract.View.initData(entity: WhoLikeMeEntity.Data?) {
        entity?.apply {
            if (page.page == 1) {
                list.clear()
            }
            this@WhoLikeMePresenter.wlmNum = entity.wlmNum
            this@WhoLikeMePresenter.message = entity.message
            setWlmNum(txtLikeMeFragSize,wlmNum,entity.isMember)
            SDEventManager.post(wlmNum, EnumEventTag.REFRESH_WLM_LIKE_SIZE.ordinal)
            for (i in 0 until entity.wlmList.size) {
                Glide.with(mActivity)
                    .load(entity.wlmList[i].avatarUrl)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .preload()
            }

//            if (!BaseConfig.getInstance.getBoolean(SpName.firstIntoWLM, false) && !entity.isMember) {
//                if (wlmNum != 0 && entity.wlmUsageNum != "0") {
//                    FirstIntoWLMDialog(
//                        mActivity,
//                        entity.wlmWindow,
//                        entity.wlmUsageNum
//                    ).showPopupWindow(whoLikeMeList)
//                }
//            }
            member = entity.isMember
            whoLikeMeAdapter?.setMember(member)
            txtLikeMeFragPremiumUnlock.visibility = if (member) View.GONE else {
                if (entity.wlmNum != 0) View.VISIBLE else View.GONE
            }
            list.addAll(entity.wlmList)
            conLikeMeFragEmpty.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE
            refreshLayoutLikeMeFrag.visibility = if (list.isEmpty()) View.GONE else View.VISIBLE
            refreshLayoutLikeMeFrag.setNoMoreData(entity.wlmList.size != page.pageSize)
            refreshLayoutLikeMeFrag.setEnableFooterFollowWhenNoMoreData(true)
            whoLikeMeAdapter!!.notifyDataSetChanged()
            txtLikeMeFragPremiumUnlock.visibility = if (member) View.GONE else {
                if (CollectionUtils.isNotEmpty(list)) View.VISIBLE else View.GONE
            }
        }

    }

    private fun userAction(direction: Int, whoLikeMeListBean: WhoLikeMeListBean) {
        mView?.apply {
            wlmNum -= 1
            setWlmNum(txtLikeMeFragSize,wlmNum,member)
            SDEventManager.post(wlmNum, EnumEventTag.REFRESH_WLM_LIKE_SIZE.ordinal)
            val position = list.indexOf(whoLikeMeListBean)
            list.remove(whoLikeMeListBean)
//            whoLikeMeAdapter!!.notifyItemRemoved(position)
            whoLikeMeAdapter!!.notifyDataSetChanged()
            if (wlmNum <= 1) {
                getData()
            }
            conLikeMeFragEmpty.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE
            txtLikeMeFragPremiumUnlock.visibility = if (member) View.GONE else {
                if (list.isEmpty()) View.GONE else View.VISIBLE
            }

            refreshLayoutLikeMeFrag.visibility = if (list.isEmpty()) View.GONE else View.VISIBLE
            if (direction == ItemTouchHelper.END) {
                val bundle = Bundle()
                bundle.putString("userCodeFriend", whoLikeMeListBean.userCodeFriend)
                bundle.putString(
                    "avatarUrl",
                    whoLikeMeListBean.avatarUrl
                )
                IntentUtil.startActivity(MatchedActivity::class.java, bundle)
            }
        }
    }

    fun removeData(position: Int) {
        mView?.apply {
            list.removeAt(position)
            whoLikeMeAdapter?.notifyItemRemoved(position)
            if (list.isEmpty()) {
                txtLikeMeFragPremiumUnlock.visibility = View.GONE
            }

        }
    }

    fun benefitsReduceWLM(friendUserCode: String, type: Int, callBack: EmptyCallBack) {
        return OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
            override fun addBody(requestBody: OkHttpBodyEntity) {
                requestBody.setPost(Constant.user_benefits_reduceWLM_url)
                requestBody.add("likeType", type)
                requestBody.add("userCodeFriend", friendUserCode)
            }
        }, object : SDOkHttpResoutCallBack<BaseEntity>() {
            override fun onSuccess(entity: BaseEntity) {
                callBack.OnSuccessListener()
            }

            override fun onFailure(code: Int, msg: String) {
                when (code) {
                    HttpResultCode.NEED_BUG_MEMBER -> {
                        FirebaseEventUtils.logEvent(if (type == 1) FirebaseEventTag.WLM_Like_Sub.name else FirebaseEventTag.WLM_Pass_Sub.name)
                        MemberBuyPopup(
                            mActivity,
                            1,
                            object : MemberBuyPopup.ChangeMembershipListener {
                                override fun onListener(bean: MemberSubscribeEntity.Data.ProductDescriptions) {
                                    OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                                        override fun addBody(requestBody: OkHttpBodyEntity) {
                                            requestBody.setPost(Constant.user_create_order_url)
                                            requestBody.add("productCode", bean.productCode)
                                            requestBody.add("productCategory", 1)
                                        }

                                    }, object : SDOkHttpResoutCallBack<OrderCreateEntity>() {
                                        override fun onSuccess(entity: OrderCreateEntity) {
                                            GooglePayUtils.instance.start(
                                                entity,
                                                mActivity,
                                                object : EmptySuccessCallBack {
                                                    override fun OnSuccessListener() {
                                                        page.initialRefresh()
                                                        FirebaseEventUtils.logEvent(if (type == 1) FirebaseEventTag.WLM_Like_Subsuccess.name else FirebaseEventTag.WLM_Pass_Subsuccess.name)
                                                        getData()
                                                        BaseConfig.getInstance.setBoolean(
                                                            SpName.isMember,
                                                            true
                                                        )
                                                    }

                                                })
                                        }
                                    })
                                }

                                override fun closeListener(refreshTime: Long) {
                                }

                            })
                    }
                }
            }
        }, isShowDialog = false)

    }

    fun addItem(bean: WhoLikeMeListBean) {
        mView?.apply {
            if (CollectionUtils.isNotEmpty(list)) {
                list.add(0, bean)
                wlmNum = list.size
                SDEventManager.post(wlmNum, EnumEventTag.REFRESH_WLM_LIKE_SIZE.ordinal)
                whoLikeMeAdapter!!.notifyItemInserted(0)
            } else {
                list.add(0, bean)
                wlmNum = list.size
                SDEventManager.post(wlmNum, EnumEventTag.REFRESH_WLM_LIKE_SIZE.ordinal)
//                if (!BaseConfig.getInstance.getBoolean(SpName.firstIntoWLM, false)) {
//                    if (wlmNum != 0 && data?.wlmUsageNum != "0") {
//                        FirstIntoWLMDialog(
//                            mActivity,
//                            data?.wlmWindow ?: "0",
//                            data?.wlmUsageNum ?: "0"
//                        ).showPopupWindow(whoLikeMeList)
//                    }
//                }
                setWlmNum(txtLikeMeFragSize,wlmNum,member)
                txtLikeMeFragPremiumUnlock.visibility = if (member) View.GONE else {
                    if (data?.wlmNum != 0) View.VISIBLE else View.GONE
                }
                conLikeMeFragEmpty.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE
                refreshLayoutLikeMeFrag.visibility = if (list.isEmpty()) View.GONE else View.VISIBLE
                whoLikeMeAdapter!!.notifyItemInserted(0)
            }

        }

    }
    fun setWlmNum(txtWlmSize: TextView, wlmNum: Int, member: Boolean) {
        if (wlmNum < 1 && member){
            txtWlmSize.isVisible = false
            return
        }
        txtWlmSize.isVisible = true
        txtWlmSize.text = if (member) "$wlmNum people have already liked you \uD83D\uDC97" else "Go Premium for instant matches and unlocked features!"
        txtWlmSize.textSize = if (member) 15f else 12f
        txtWlmSize.setTextColor(if (member) ContextCompat.getColor(mActivity, R.color.color_CBC3D2) else ContextCompat.getColor(mActivity, R.color.color_9C9FA6))
    }

    fun getData() {
        mView?.apply {
            OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                override fun addBody(requestBody: OkHttpBodyEntity) {
                    requestBody.setPost(Constant.user_wlm_list_url)
                    requestBody.addPage(page)
                }
            }, object : SDOkHttpResoutCallBack<WhoLikeMeEntity>() {
                override fun onSuccess(entity: WhoLikeMeEntity) {
                    if (page.page == 1) {
                        list.clear()
                    }
                    if (entity.data.wlmList.isNotEmpty()) {
                        for (i in 0 until entity.data.wlmList.size) {
                            Glide.with(mActivity)
                                .load(entity.data.wlmList[i].avatarUrl)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .preload()
                        }

                        whoLikeMeAdapter?.setMember(entity.data.isMember)
                        list.addAll(entity.data.wlmList)
                        refreshLayoutLikeMeFrag.setNoMoreData(entity.data.wlmList.size != page.pageSize)
                        refreshLayoutLikeMeFrag.setEnableFooterFollowWhenNoMoreData(true)
                        whoLikeMeAdapter?.notifyDataSetChanged()
                    }
                    conLikeMeFragEmpty.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE
                    refreshLayoutLikeMeFrag.visibility = if (list.isEmpty()) View.GONE else View.VISIBLE
                    wlmNum = entity.data.wlmNum
                    setWlmNum(txtLikeMeFragSize,wlmNum,entity.data.isMember)

                    SDEventManager.post(wlmNum, EnumEventTag.REFRESH_WLM_LIKE_SIZE.ordinal)

                    txtLikeMeFragPremiumUnlock.visibility = if (entity.data.isMember) View.GONE else {
                        if (CollectionUtils.isNotEmpty(list)) View.VISIBLE else View.GONE
                    }
                }

                override fun onFinish() {
                    if (refreshLayoutLikeMeFrag!= null) {
                        if (page.page == 1) {
                            refreshLayoutLikeMeFrag.finishRefresh(920)
                        } else {
                            refreshLayoutLikeMeFrag.finishLoadMore(1000)
                        }
                    }
                }
            })
        }
    }


    fun refreshItem(userCode: String, onlineStatus: Int) {
        whoLikeMeAdapter?.let {var position = 0
            for (i in 0 until whoLikeMeAdapter!!.dataList.size) {
                if (whoLikeMeAdapter!!.dataList[i].userCodeFriend == userCode) {
                    position=i
                    whoLikeMeAdapter!!.dataList[i].online =onlineStatus
                    break
                }
            }
            whoLikeMeAdapter!!.notifyItemChanged(position)
        }

    }
}